<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back" @click="navigateBack">
        <uni-icons type="left" size="20" color="#fff"></uni-icons>
      </view>
      <view class="title">我的车辆</view>
      <view class="right">
        <uni-icons type="more-filled" size="20" color="#fff"></uni-icons>
      </view>
    </view>

    <!-- 背景色块 -->
    <view class="bg"></view>

    <!-- 加载中状态 -->
    <view class="loading-state" v-if="loading">
      <uni-load-more status="loading" />
    </view>

    <!-- 空状态展示 -->
    <view class="empty-state" v-else-if="carList.length === 0">
      <image class="empty-image" src="/static/empty-car.png" mode="aspectFit"></image>
      <text class="empty-text">暂无车辆信息</text>
    </view>

    <!-- 车辆列表 -->
    <view class="car-list" v-else>
      <view class="car-item" v-for="car in carList" :key="car.id">
        <view class="car-info">
          <image class="car-image" :src="car.carType?.img || '/static/whb/car1.jpg'" mode="aspectFill"></image>
          <view class="info-content">
            <view class="car-type">车型：{{ car.carType?.name }}</view>
            <view class="car-number">车牌：{{ car.carNum }}</view>
            <view class="car-brand" v-if="car.carBrand">品牌：{{ car.carBrand.name }}</view>
            <view class="car-color" v-if="car.carType?.color">颜色：{{ car.carType.color }}</view>
          </view>
          <button class="action-btn delete" @click="handleDeleteCar(car)">删除</button>
        </view>
        <view class="car-actions">
          <view class="default-radio" @click="setDefaultCar(car.id)">
            <text v-if="car.defaultCar === 1" class="radio-checked">●</text>
            <text v-else class="radio-unchecked">○</text>
            <text class="default-label">设为默认车辆</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部添加按钮 -->
    <view class="bottom-btn">
      <button class="add-btn" @click="navigateToAddCar">
        <text class="plus">+</text>
        <text>添加车辆</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 响应式数据
const carList = ref([]);
const loading = ref(false);

// 获取车辆列表
const fetchCarList = (id) => {
  if (!id) {
    uni.showToast({
      title: '用户ID不能为空',
      icon: 'none'
    });
    return;
  }

  loading.value = true;
  uni.request({
    url: 'http://localhost:9402/carinfo/user/' + id,
    method: 'GET',
    header: {
      'Authorization': uni.getStorageSync('Token')
    },
    success: (res) => {
      if (res.statusCode === 200 && res.data.code === 200) {
        carList.value = res.data.data || [];
      } else {
        uni.showToast({
          title: res.data.msg || '获取车辆列表失败',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      console.error('获取车辆列表失败:', err);
      uni.showToast({
        title: '网络请求失败',
        icon: 'none'
      });
    },
    complete: () => {
      loading.value = false;
    }
  });
};

// 设置默认车辆
const setDefaultCar = (id) => {
  // 找到当前默认车辆
  const currentDefaultCar = carList.value.find(car => car.defaultCar === 1);
  
  // 如果当前默认车辆存在且不是要设置的新默认车辆，先将其设置为非默认
  if (currentDefaultCar && currentDefaultCar.id !== id) {
    uni.request({
      url: 'http://localhost:9402/carinfo',
      method: 'PUT',
      header: {
        'Authorization': uni.getStorageSync('Token')
      },
      data: {
        id: currentDefaultCar.id,
        defaultCar: 0
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          // 设置新的默认车辆
          setNewDefaultCar(id);
        } else {
          uni.showToast({
            title: res.data.msg || '设置失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  } else {
    // 如果没有当前默认车辆，直接设置新的默认车辆
    setNewDefaultCar(id);
  }
};

// 设置新的默认车辆
const setNewDefaultCar = (id) => {
  uni.request({
    url: 'http://localhost:9402/carinfo',
    method: 'PUT',
    header: {
      'Authorization': uni.getStorageSync('Token')
    },
    data: {
      id: id,
      defaultCar: 1
    },
    success: (res) => {
      if (res.statusCode === 200 && res.data.code === 200) {
        // 更新本地数据
        carList.value = carList.value.map(car => ({
          ...car,
          defaultCar: car.id === id ? 1 : 0
        }));
        uni.showToast({
          title: '设置成功',
          icon: 'success'
        });
      } else {
        uni.showToast({
          title: res.data.msg || '设置失败',
          icon: 'none'
        });
      }
    },
    fail: () => {
      uni.showToast({
        title: '网络请求失败',
        icon: 'none'
      });
    }
  });
};

// 删除车辆
const handleDeleteCar = (car) => {
  uni.showModal({
    title: '提示',
    content: `确定要删除车牌号为 ${car.carNum} 的车辆吗？`,
    success: (res) => {
      if (res.confirm) {
        uni.request({
          url: 'http://localhost:9402/carinfo/' + car.id,
          method: 'DELETE',
          header: {
            'Authorization': uni.getStorageSync('Token')
          },
          success: (res) => {
            if (res.statusCode === 200 && res.data.code === 200) {
              carList.value = carList.value.filter(item => item.id !== car.id);
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
            } else {
              uni.showToast({
                title: res.data.msg || '删除失败',
                icon: 'none'
              });
            }
          },
          fail: () => {
            uni.showToast({
              title: '网络请求失败',
              icon: 'none'
            });
          }
        });
      }
    }
  });
};

// 导航返回
const navigateBack = () => {
  uni.switchTab({
    url: '/pages/my/my'
  });
};

// 跳转到添加车辆页面
const navigateToAddCar = () => {
  const id = uni.getStorageSync('user').id;
  uni.navigateTo({
    url: `/pages/my/mycar/AddCar?id=${id}`
  });
};

// 页面加载钩子
onLoad((options) => {
  if (options.id) {
    fetchCarList(options.id);
  } else {
    uni.showToast({
      title: '缺少用户ID参数',
      icon: 'none'
    });
  }
});
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  padding-bottom: 100px;
}

.nav-bar {
  display: flex;
  align-items: center;
  height: 44px;
  background-color: #007AFF;
  color: #fff;
  padding: 0 15px;
  
  .back, .right {
    width: 44px;
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 18px;
    font-weight: 500;
  }
  
  .right {
    text-align: right;
  }
}

.bg {
  width: 100%;
  height: 250rpx;
  background-color: #007AFF;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  margin-top: -200rpx;
  background-color: #fff;
  border-radius: 20px 20px 0 0;
  min-height: 200px;
}

.empty-state {
  margin: 10px 10px 0;
  margin-top: -200rpx;
  border-radius: 20px 20px 0 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 150px;
  background-color: #fff;
  
  .empty-image {
    width: 200px;
    height: 200px;
    margin-bottom: 20px;
  }
  
  .empty-text {
    font-size: 14px;
    color: #999;
  }
}

.car-list {
  margin: 10px 10px 0;
  margin-top: -200rpx;
  border-radius: 20px 20px 0 0;
  padding: 15px;
  background-color: #fff;
  
  .car-item {
    background-color: #fff;
    border-radius: 16px;
    margin-bottom: 20px;
    padding: 20px 16px 10px 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    position: relative;
    .car-info {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      position: relative;
      .car-image {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        margin-right: 16px;
        object-fit: cover;
      }
      .info-content {
        flex: 1;
        .car-type {
          font-size: 16px;
          color: #222;
          font-weight: 500;
          margin-bottom: 4px;
        }
        .car-number {
          font-size: 15px;
          color: #666;
        }
        .car-brand {
          font-size: 14px;
          color: #666;
          margin-top: 4px;
        }
        .car-color {
          font-size: 14px;
          color: #666;
          margin-top: 4px;
        }
      }
      .action-btn.delete {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        background: none;
        color: #888;
        border: none;
        font-size: 14px;
        padding: 0 8px;
        height: 28px;
        line-height: 28px;
        border-radius: 14px;
        box-shadow: none;
      }
    }
    .car-actions {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 8px;
      .default-radio {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: #888;
        cursor: pointer;
        .radio-checked {
          color: #FF9900;
          font-size: 18px;
          margin-right: 4px;
        }
        .radio-unchecked {
          color: #bbb;
          font-size: 18px;
          margin-right: 4px;
        }
        .default-label {
          margin-right: 8px;
        }
      }
    }
  }
}

.bottom-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  
  .add-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 44px;
    background-color: #007AFF;
    color: #fff;
    border-radius: 22px;
    font-size: 16px;
    
    .plus {
      font-size: 20px;
      margin-right: 5px;
    }
  }
}
</style>